import React from 'react';
import { Table, Button, Input, Row, Col, Form, Modal, Radio } from 'antd';
import { connect } from 'dva';

const search = Input.Search;
const Search = search;
const { TextArea } = Input;
const FormItem = Form.Item;

const columns = [{
  title: '商品类型',
  dataIndex: 'type_name',
}, {
  title: '备注',
  dataIndex: 'memo',
}, {
  title: '是否可用',
  dataIndex: 'status',
}];

class CommodityType extends React.Component {
    state = {
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      isShow: true,
      data: [],
      visible: false,
      modelTitle: '',
      modelButton: '',
    };

    componentDidMount() {
      this.props.dispatch({
        type: 'commoditytype/getCommodityType',
        payload: {
          page_no: 1,
          page_size: 20,
        },
      });
    }

    componentWillReceiveProps(nextProps) {
      this.setState({
        data: nextProps.commoditytype.commoditytypeList,
      });
    }

      onSelectChange = (selectedRowKeys) => {
        // console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({
          selectedRowKeys,
        });
      }
      handleButtonClick = (oper) => {
        switch (oper) {
          case '新增':
            this.setState({
              modelTitle: `${oper}商品类型`,
              modelButton: oper,
              visible: !this.state.visible,
            });
            break;
          case '修改':
            this.setState({
              modelTitle: `${oper}商品类型`,
              modelButton: oper,
              visible: !this.state.visible,
            });
            break;
          case '删除':
            this.handleDelete();
            break;
          default:
            break;
        }
      }
      handleCancel = () => {
        this.setState({ visible: !this.state.visible });
      }
      handleModel = (modelButton) => {
        const forms = this.props.form;
        forms.validateFields((err, values) => {
          if (err) {
            return;
          }
          if (modelButton === '新增') {
            this.props.dispatch({
              type: 'commoditytype/addCommodityType',
              payload: {
                type_name: values.type_name,
                status: values.status,
                memo: values.memo,
              },
            });
          } else {
            this.props.dispatch({
              type: 'commoditytype/updateCommodityType',
              payload: {
                id: this.state.data[this.state.selectedRowKeys[0]]._id,
                type_name: values.type_name,
                status: values.status,
                memo: values.memo,
              },
            });
            this.setState({
              selectedRowKeys: [],
            });
          }

          forms.resetFields();
          this.setState({ visible: !this.state.visible });
        });
      }
      handleSearch = (id) => {
        this.props.dispatch({
          type: 'commoditytype/searchCommodityType',
          payload: {
            id,
          },
        });
      }
      handleDelete = () => {
        this.state.selectedRowKeys.map((record) => {
          return (
            this.props.dispatch({
              type: 'commoditytype/deleteCommodityType',
              payload: {
                id: this.state.data[record]._id,
              },
            })
          );
        });
        this.setState({
          selectedRowKeys: [],
        });
      }
      render() {
        const { loading, selectedRowKeys } = this.state;
        const rowSelection = {
          selectedRowKeys,
          onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length;
        const { getFieldDecorator } = this.props.form;

        const operations = [
          {
            name: '新增',
            disabled: !this.state.isShow,
          },
          {
            name: '修改',
            disabled: hasSelected === 1 ? false : this.state.isShow,
          },
          {
            name: '删除',
            disabled: hasSelected > 0 ? false : this.state.isShow,
          },
        ];
        return (
          <Row>
            <Row style={{ marginBottom: 16 }} type="flex" justify="space-between">
              <Col span={16}>
                {
                  operations.map((oper) => {
                          return (
                            <Button
                              key={oper.name}
                              type="primary"
                              onClick={() => this.handleButtonClick(oper.name)}
                              disabled={oper.disabled}
                              loading={loading}
                              style={{ marginRight: 10 }}
                            >
                              {oper.name}
                            </Button>
                          );
                      })
                  }
                <span style={{ marginLeft: 8 }}>
                  {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
                </span>
              </Col>
              <Col span={8}>
                <Search
                  placeholder="请输入id（5af54b63af5c6c19face09b7）"
                  onSearch={value => this.handleSearch(value)}
                  enterButton
                  style={{ width: '100%' }}
                />
              </Col>
            </Row>
            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={this.state.data}
              pagination={{
                // total: 50,
                defaultPageSize: 5,
                pageSize: 5,
                showTotal: () => {
                    // 设置显示一共几条数据
                    return `共 ${this.state.data.length} 条数据`;
                },
              }}
            />
            <Row>
              <Modal
                visible={this.state.visible}
                title={this.state.modelTitle}
                okText={this.state.modelButton}
                cancelText="取消"
                onCancel={this.handleCancel}
                onOk={() => this.handleModel(this.state.modelButton)}
              >
                <Form layout="vertical">
                  <FormItem label="类型名称">
                    {getFieldDecorator('type_name', {
                rules: [{ required: true, message: '请输入商品类型名称!' }],
              })(
                <Input />
              )}
                  </FormItem>
                  <FormItem label="备注">
                    {getFieldDecorator('memo')(
                      <TextArea placeholder="商品类型描述或备注..." autosize={{ minRows: 2, maxRows: 6 }} />)}
                  </FormItem>
                  <FormItem className="collection-create-form_last-form-item">
                    {getFieldDecorator('status', {
                          initialValue: 0,
                        })(
                          <Radio.Group>
                            状态（是否启用）：
                            <Radio value={0}>是</Radio>
                            <Radio value={1}>否</Radio>
                          </Radio.Group>
                        )}
                  </FormItem>
                </Form>
              </Modal>
            </Row>
          </Row>
        );
      }
}

const CommodityTypeWrap = Form.create()(CommodityType);

export default connect(({ commoditytype }) => ({
  commoditytype,
}))(CommodityTypeWrap);
